<?php
namespace App\Http\Controllers;
use App\Pay\ItpPay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class Pay2Controller extends Controller
{   
  
    public function toPay(){
        /* 
            请求参数，参数须按字符升序排列
        */
        $itppay_config['appid']  = getenv('PayAppId');
        $itppay_config['key'] = getenv('PayAppKey');
        
        $parameter=array(
                "amount"         =>"1000000",//[必填]订单总金额，单位(分)
                "appid"          =>$itppay_config['appid'],//[必填]//交易发起所属app
                "body"           =>"毅思科技服务费",//[必填]商品描述
                "clientIp"       =>"192.168.1.1",//[必填]客户端IP
                "cpChannel"      =>"",//CP分发渠道
                "currency"       =>"",//币种，默认RMB
                "description"    =>"",//订单附加描述
                "expireMs"       =>"",//过期时间毫秒数，默认24小时过期
                "extra"          =>"",//附加数据，以键值对形式存放，例如{"key":"value"}
                "mchntOrderNo"   =>date("Y").date("m").date("d").rand(10000,100000),//[必填]商户订单号，必须唯一性
                "notifyUrl"      =>"http://local.eajyq.com/notify",//[必填]订单支付结果异步通知地址，用于接收订单支付结果通知，必须以http或https开头
                "returnUrl"      =>"http://local.eajyq.com/home",//[必填]订单支付结果同步跳转地址，用于同步跳转到商户页面，必须以http或https开头
                "subject"        =>"毅思（北京）科技有限责任公司",//[必填]商品名称
                "version"        =>"pc_NoEncrypt",//接口版本号，值为pc_NoEncrypt时,则明天平台返回商户参数时，不进行RSA加密
                "payChannelId"   =>"6000000003"//支付渠道id
        );
     
        /* *
        * 建立请求
        */
        $itpPay = new ItpPay($itppay_config);
        $url = $itpPay->itppay_gateway;
        $orderInfo=$itpPay->getOrderInfo($parameter);
//        $html=$itpPay->RequestForm($orderInfo,'正在跳转到支付页面...');
//        echo $html;
        $data = array("orderInfo" => $orderInfo);                                                                      
        $ch = curl_init($url);   
        curl_setopt($ch, CURLOPT_POST, 1);    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  
        $result = curl_exec($ch);
        curl_close($ch);
        $qrcode = json_decode($result);
        dd($qrcode->QRCode);
       
    }
    
    //订单支付结果异步通知地址，用于接收订单支付结果通知
    public function notify(){
        /* *
        * 获取传递数据
        */
       $data = file_get_contents("php://input");

       $parameter = json_decode($data, true);
       $signature = $parameter["signature"];
       unset($parameter["signature"]);

       /* *
        * 签名
        */
       $itpPay = new ItpPay($itppay_config);
       $signature_local=$itpPay->setSignature($parameter);

       $logFile = fopen("log.txt", "a+");
       fclose(fopen("log2.txt","w"));
       $logFile2 = fopen("log2.txt", "a+");
       if($signature && $signature == $signature_local){
	
            //$parameter["orderNo"]明天云平台生成的订单号
            //$parameter["mchntOrderNo"]商户订单号，可根据商户订单号查询商户网站中该订单信息，并执行业务处理
            //$parameter["orderDt"]下单日期
            //$parameter["paidTime"]订单支付完成时间
            //$parameter["extra"]附加数据
            //$parameter["paySt"]支付结果状态，0:待支付；1:支付中；2:支付成功；3:支付失败；4:已关闭
	
            switch($parameter["paySt"]){
		case 0:
			fwrite($logFile, "[".$parameter["mchntOrderNo"]."]--->待支付\r\n");
			fwrite($logFile2, "[".$parameter["mchntOrderNo"]."]--->待支付\r\n");
			break;
		case 1:
			fwrite($logFile, "[".$parameter["mchntOrderNo"]."]--->支付中\r\n");
			fwrite($logFile2, "[".$parameter["mchntOrderNo"]."]--->支付中\r\n");
			break;
		case 2:
			fwrite($logFile, "[".$parameter["mchntOrderNo"]."]--->支付成功\r\n");
			fwrite($logFile2, "[".$parameter["mchntOrderNo"]."]--->支付成功\r\n");
			break;
		case 3:
			fwrite($logFile, "[".$parameter["mchntOrderNo"]."]--->支付失败\r\n");
			fwrite($logFile2, "[".$parameter["mchntOrderNo"]."]--->支付失败\r\n");
			break;
		case 4:
			fwrite($logFile, "[".$parameter["mchntOrderNo"]."]--->已关闭\r\n");
			fwrite($logFile2, "[".$parameter["mchntOrderNo"]."]--->已关闭\r\n");
			break;
	}
	
            foreach($parameter as $k=>$v){
                    fwrite($logFile, $k."=".$v."\r\n");
                    fwrite($logFile2, $k."=".$v."\r\n");
            }
            fwrite($logFile, "\r\n\r\n");
            fwrite($logFile2, "\r\n\r\n");
	
        }else{
                fwrite($logFile, "[".$parameter["mchntOrderNo"]."]--->验签失败\r\n");
                fwrite($logFile2, "[".$parameter["mchntOrderNo"]."]--->验签失败\r\n");
        }
        fclose($logFile);
        fclose($logFile2);
        echo "{\"success\":\"true\"}";
    }
    //支付
    public function pay(Request $request){
        return view('pay');
    }
    // 支付的第二页面
    public function paytwo(Request $request){
//        $order_num = trim($request->order_num);
//        dd($order_num);
        $isYh          = intval(trim($request->isYH)); //是不是优惠了
        $buyMonth      = intval(trim($request->yhMonth)); //购买几个月
        $isBuyVps      = intval(trim($request->isbuyvps)); //是不是购买了vps
        $pirect        = $isYh == 1 ? 2499 : 2999; //每个月的价格
        $buyVpsMoney   = $isBuyVps == 1 ? ($buyMonth*200) : 0; //购买vps的总金额
        $cpMoney       = $buyMonth == 12 ? (10*$pirect) : ($buyMonth*$pirect); //购买插件的总金额
        $totalMoney    = $buyVpsMoney + $cpMoney;//需要付款的总金额
        $allMoney      = $buyVpsMoney + ($buyMonth*2999);//没有优惠的总金额
        $yhMoney       = $allMoney-$totalMoney;//优惠的总金额
        return view('pay_next',compact('buyVpsMoney','cpMoney','totalMoney','allMoney','yhMoney','buyMonth'));
    }
    //提交产品
    public function addPay(Request $request){
        $sessiondata   = $request->session()->get('eai');
        if(!$sessiondata){
            return json_encode(array('status'=>0,'msg'=>'用户未登录'));
        }
        $isYh          = intval(trim($request->isYH)); //是不是优惠了
        $buyMonth      = intval(trim($request->yhMonth)); //购买几个月
        if(!$buyMonth){
            return json_encode(array('status'=>1,'msg'=>'请选择购买的类型'));
        }
        $isBuyVps      = intval(trim($request->isbuyvps)); //是不是购买了vps
        $pirect        = $isYh == 1 ? 2499 : 2999; //每个月的价格
        $buyVpsMoney   = $isBuyVps == 1 ? ($buyMonth*200) : 0; //购买vps的总金额
        $cpMoney       = $buyMonth == 12 ? (10*$pirect) : ($buyMonth*$pirect); //购买插件的总金额
        $totalMoney    = $buyVpsMoney + $cpMoney;//总金额
        $buyorderid    = GetBuyOrderId();//获取唯一订单号
        //入库数据
        $data = array(
                        'userid'=>$sessiondata['id'],
                        'order_num'=>$buyorderid,
                        'buy_month'=>$buyMonth,
                        'status'=>1,
                        'is_buy_vps'=>$isBuyVps,
                        'is_yh'=>$isYh,
                        'money'=>$totalMoney,
                        'order_time'=>time()
                    );
        $id = DB::table('waihui_pay_log')->insertGetId($data);
        if($id){
            return json_encode(array('status'=>2,'msg'=>'提交成功','order_num'=>$buyorderid));
        }else{
            return json_encode(array('status'=>3,'msg'=>'提交失败'));
        }
    }
}
